package com.rdc.qingkou.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.percent.PercentRelativeLayout;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.rdc.qingkou.Application.MyApplication;
import com.rdc.qingkou.R;
import com.rdc.qingkou.base.BaseActivity;
import com.rdc.qingkou.presenter.BrowseDetailPresenter;
import com.rdc.qingkou.ui.iview.IBrowseDetailView;
import com.rdc.qingkou.utils.MyUtils;
import com.rdc.qingkou.vo.CardVO;

import java.io.IOException;

import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;

public class BrowseDetailActivity extends BaseActivity<BrowseDetailPresenter> implements IBrowseDetailView, View.OnClickListener, MediaPlayer.OnPreparedListener {

    public static final int DELETED = 1;
    public static final int NOT_DELETE = 2;

    private TabLayout mTabLayout;
    private boolean mIsCollected;
    private boolean mIsAppreciated;
    private CardVO mCard;
    private ProgressDialog mDeleteProgressDialog;
    private AlertDialog.Builder mDeleteAlertDialog;
    private ProgressBar mVoiceProgressBar;
    private MediaPlayer mMediaPlayer = null;
    private boolean isPrepared = false;//音频是否准备好
    private boolean isPlaying = true;
    private final static int APPRECIATE = 3;
    private final static int COLLECTED = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
        setContentView(R.layout.activity_browse_detail);
        mCard = (CardVO) getIntent().getSerializableExtra("card");
        initViews();
        if (MyUtils.isNetworkConnected(this)) {
            mPresenter.getCardStatus(MyApplication.getUser().getUserId(), mCard.getCardId());
        } else {
            Toast.makeText(this, "无网络！", Toast.LENGTH_SHORT).show();
        }
    }

    private void initViews() {
        int height = MyUtils.getStatusBarHeight(BrowseDetailActivity.this);
        ImageButton backImageButton = (ImageButton) findViewById(R.id.browse_detail_back_imageButton);
        backImageButton.setOnClickListener(this);
        //调整返回键的位置
        PercentRelativeLayout.LayoutParams backButtonParams = (PercentRelativeLayout.LayoutParams) backImageButton.getLayoutParams();
        backButtonParams.setMargins(MyUtils.dp2px(BrowseDetailActivity.this, 10), MyUtils.dp2px(BrowseDetailActivity.this, 15) + height, 0, 0);
        backImageButton.setLayoutParams(backButtonParams);

        ImageButton menuImageButton = (ImageButton) findViewById(R.id.browse_detail_menu_imageButton);

        if (mCard.isMyCard()) {
            mDeleteAlertDialog = new AlertDialog.Builder(BrowseDetailActivity.this);
            mDeleteAlertDialog.setTitle("提示");
            mDeleteAlertDialog.setMessage("确认删除该卡片吗？");
            mDeleteAlertDialog.setCancelable(true);
            mDeleteAlertDialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    mPresenter.deleteCard(mCard.getCardId());
                    mDeleteProgressDialog.show();
                }
            });
            mDeleteAlertDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });
            mDeleteProgressDialog = new ProgressDialog(BrowseDetailActivity.this);
            mDeleteProgressDialog.setMessage("删除中");
            mDeleteProgressDialog.setCancelable(true);
            //调整菜单键的位置
            menuImageButton.setOnClickListener(this);
            PercentRelativeLayout.LayoutParams menuButtonParams = (PercentRelativeLayout.LayoutParams) menuImageButton.getLayoutParams();
            menuButtonParams.setMargins(0, MyUtils.dp2px(BrowseDetailActivity.this, 15) + height, MyUtils.dp2px(BrowseDetailActivity.this, 10), 0);
            menuImageButton.setLayoutParams(menuButtonParams);
        } else {
            menuImageButton.setVisibility(View.GONE);
        }

        mVoiceProgressBar = (ProgressBar) findViewById(R.id.browse_detail_voice_progress_progressBar);
        TextView text = (TextView) findViewById(R.id.browse_detail_text_textView);
        text.setText(mCard.getContent());
        JZVideoPlayerStandard player = (JZVideoPlayerStandard) findViewById(R.id.browse_detail_videoPlayer);
        ImageView voice = (ImageView) findViewById(R.id.browse_detail_voice_imageView);
        ImageView image = (ImageView) findViewById(R.id.browse_detail_image_imageView);
        if (mCard.getMediaUrl() != null) {
            //视频，则不显示图片和音频
            image.setVisibility(View.GONE);
            voice.setVisibility(View.GONE);
            mVoiceProgressBar.setVisibility(View.GONE);
            player.setVisibility(View.VISIBLE);
            player.setUp(mCard.getMediaUrl(), JZVideoPlayer.SCREEN_LAYOUT_LIST, "");
            //设置封面
            //mPlayer.thumbImageView.setImageBitmap(MyUtils.getNetVideoBitmap(URL.HEAD_YUN + mCard.getMediaUrl()));
        } else {
            //图片
            Glide.with(this).load(mCard.getImageUrl()).placeholder(R.mipmap.ic_launcher).into(image);
            if (mCard.getVoiceUrl() != null) {
                voice.setOnClickListener(this);
            } else {
                voice.setVisibility(View.GONE);
                mVoiceProgressBar.setVisibility(View.GONE);
            }
        }

        mTabLayout = (TabLayout) findViewById(R.id.browse_detail_tabLayout);
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                selected(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                selected(tab.getPosition());
            }
        });

    }

    private void updateVoiceProgress() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isPlaying) {
                    mVoiceProgressBar.setProgress(mMediaPlayer.getCurrentPosition());
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    public void setCardStatus(boolean isCollected, boolean isAppreciated) {
        mIsCollected = isCollected;
        mIsAppreciated = isAppreciated;
        if (mIsCollected) {
            mTabLayout.getTabAt(COLLECTED).setIcon(R.drawable.button_collect_pressure);
        }
        if (mIsAppreciated) {
            mTabLayout.getTabAt(APPRECIATE).setIcon(R.drawable.button_appreciate_pressure);
        }
    }

    @Override
    public void getCardStatusError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void appreciateSuccess(boolean status) {
        mIsAppreciated = status;
        if (mIsAppreciated) {
            mTabLayout.getTabAt(APPRECIATE).setIcon(R.drawable.button_appreciate_pressure);
        } else {
            mTabLayout.getTabAt(APPRECIATE).setIcon(R.drawable.button_appreciate_normal);
        }
    }

    @Override
    public void appreciateError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void collectSuccess(boolean status) {
        mIsCollected = status;
        if (mIsCollected) {
            mTabLayout.getTabAt(COLLECTED).setIcon(R.drawable.button_collect_pressure);
        } else {
            mTabLayout.getTabAt(COLLECTED).setIcon(R.drawable.button_collect_normal);
        }
    }

    @Override
    public void collectError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void deleteCardResult(String result, boolean success) {
        if (success) {
            Intent intent = new Intent();
            intent.putExtra("deletedCardId", mCard.getCardId());
            setResult(DELETED, intent);
            finish();
        } else {
            Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
            mDeleteProgressDialog.dismiss();
        }
    }

    @Override
    public void selected(int position) {
        if (position == 0) {
           // Toast.makeText(this, "此功能未实现！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(BrowseDetailActivity.this,ShareActivity.class);
            intent.putExtra("text",mCard.getContent());
            intent.putExtra("image",mCard.getImageUrl());
            startActivity(intent);
        } else if (position == 2) {
            Toast.makeText(this, "此功能尚未上线", Toast.LENGTH_SHORT).show();
        } else if (position == 3) {
            if (mIsAppreciated) {
                mPresenter.cancelAppreciate(MyApplication.getUser().getUserId(), mCard.getCardId());
            } else {
                mPresenter.appreciate(MyApplication.getUser().getUserId(), mCard.getCardId());
            }
        } else if (position == 4) {
            if (!mIsCollected) {
                mPresenter.collect(MyApplication.getUser().getUserId(), mCard.getCardId());
            } else {
                mPresenter.cancelCollect(MyApplication.getUser().getUserId(), mCard.getCardId());
            }
        } else if (position == 1) {
            Intent intent = new Intent(BrowseDetailActivity.this, CommentActivity.class);
            intent.putExtra("cardId", mCard.getCardId());
            startActivity(intent);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.browse_detail_back_imageButton:
                onBackPressed();
                break;
            case R.id.browse_detail_menu_imageButton:
                mDeleteAlertDialog.show();
                break;
            case R.id.browse_detail_voice_imageView:
                if (mMediaPlayer == null) {
                    Toast.makeText(this, "音频加载中", Toast.LENGTH_SHORT).show();
                    mMediaPlayer = new MediaPlayer();
                    try {
                        mMediaPlayer.setDataSource(mCard.getVoiceUrl());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mMediaPlayer.prepareAsync();
                    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mMediaPlayer.setOnPreparedListener(this);
                } else if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.pause();
                    isPlaying = false;
                } else if (isPrepared) {
                    mMediaPlayer.start();
                    isPlaying = true;
                    updateVoiceProgress();
                }
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.clearDisposable();
    }

    @Override
    public BrowseDetailPresenter getInstance() {
        return new BrowseDetailPresenter();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mMediaPlayer != null) {
            isPlaying = false;
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        mVoiceProgressBar.setMax(mMediaPlayer.getDuration());
        isPrepared = true;
        mediaPlayer.start();
        isPlaying = true;
        updateVoiceProgress();
    }


}
